<template>
  <div class="withdraw-container">
    <!-- 顶部统计卡片 -->
    <div class="stats-section">
      <div class="stat-card">
        <div class="stat-header">提现成功总额</div>
        <div class="stat-amount">¥ {{ formatAmount(totalWithdraw) }}</div>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form ref="queryRef" :model="queryParams" inline class="search-form">
        <el-form-item label="用户名">
          <el-input
            v-model="queryParams.username"
            placeholder="请输入用户名"
            clearable
            class="search-input"
          />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input
            v-model="queryParams.mobile"
            placeholder="请输入手机号"
            clearable
            class="search-input"
          />
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态" clearable class="search-select">
            <el-option label="全部" value="" />
            <el-option label="审核中" value="审核中" />
            <el-option label="审核不通过" value="审核不通过" />
            <el-option label="到账成功" value="到账成功" />
          </el-select>
        </el-form-item>
        <el-form-item label="打款方式">
          <el-select v-model="queryParams.payChannel" placeholder="请选择打款方式" clearable class="search-select">
            <el-option label="全部" value="" />
            <el-option label="微信" value="微信" />
            <el-option label="支付宝" value="支付宝" />
            <el-option label="银行卡" value="银行卡" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" class="search-btn">
            搜索
          </el-button>
          <el-button @click="resetQuery">
            重置
          </el-button>
        </el-form-item>
      </el-form>
      
      <!-- 操作按钮区域 -->
      <div class="action-buttons">
        <el-button type="success" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <div class="table-header">
        <div class="header-left">
          <span class="header-title">用户奖励金提现记录</span>
          <div class="header-tips">
            <el-tooltip content="审核中：等待平台审核" placement="top">
              <el-tag type="warning" size="small">审核中</el-tag>
            </el-tooltip>
            <el-tooltip content="审核不通过：审核被拒绝" placement="top">
              <el-tag type="danger" size="small">审核不通过</el-tag>
            </el-tooltip>
            <el-tooltip content="到账成功：提现已完成" placement="top">
              <el-tag type="success" size="small">到账成功</el-tag>
            </el-tooltip>
          </div>
        </div>
        <div class="header-stats">
          <span class="stat-item">
            总记录: <span class="total-text">{{ total }}</span>
          </span>
        </div>
      </div>
      
      <el-table 
        v-loading="loading" 
        :data="userwithdrawList" 
        stripe
        border
        style="width: 100%"
        :header-cell-style="{ backgroundColor: '#fafafa', color: '#666', fontWeight: '500' }"
      >
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column label="用户名" align="center" prop="username" min-width="100">
          <template #default="scope">
            <div class="user-info">
              <el-icon class="user-icon"><User /></el-icon>
              {{ scope.row.username }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="手机号" align="center" prop="mobile" width="120" />
        <el-table-column label="订单编号" align="center" prop="orderNo" min-width="140" show-overflow-tooltip />
        <el-table-column label="提现金额" align="center" prop="withdrawAmount" width="100">
          <template #default="scope">
            <div class="amount-cell">
              <span class="amount-text">¥{{ formatAmount(scope.row.withdrawAmount) }}</span>
              <small class="amount-label">申请</small>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="实际到账" align="center" prop="actualAmount" width="100">
          <template #default="scope">
            <div class="amount-cell">
              <span class="amount-text success">¥{{ formatAmount(scope.row.actualAmount) }}</span>
              <small class="amount-label">到账</small>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="平台手续费" align="center" prop="platformFee" width="100">
          <template #default="scope">
            <div class="amount-cell">
              <span class="fee-text">¥{{ formatAmount(scope.row.platformFee) }}</span>
              <small class="amount-label">手续费</small>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" align="center" prop="auditStatus" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.auditStatus)" size="small" effect="light">
              {{ scope.row.auditStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="审核不通过原因" align="center" prop="rejectReason" min-width="150" show-overflow-tooltip>
          <template #default="scope">
            <span v-if="scope.row.rejectReason" class="reject-reason">{{ scope.row.rejectReason }}</span>
            <span v-else class="text-muted">-</span>
          </template>
        </el-table-column>
        <el-table-column label="打款方式" align="center" prop="payChannel" width="100">
          <template #default="scope">
            <el-tag :type="getChannelType(scope.row.payChannel)" size="small">
              {{ scope.row.payChannel }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="审核时间" align="center" prop="auditTime" width="160">
          <template #default="scope">
            <div class="time-cell" v-if="scope.row.auditTime">
              <el-icon class="time-icon"><Clock /></el-icon>
              <span>{{ formatTime(scope.row.auditTime) }}</span>
            </div>
            <span v-else class="text-muted">-</span>
          </template>
        </el-table-column>

      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

  </div>
</template>

<script setup name="Userwithdraw">
import { ref, reactive, toRefs, getCurrentInstance, onMounted } from 'vue'
import { listUserwithdraw, getUserwithdraw, delUserwithdraw, addUserwithdraw, updateUserwithdraw } from "@/api/order/userwithdraw"
import { User, Clock, Download, Check, Close } from '@element-plus/icons-vue'

const { proxy } = getCurrentInstance()

const userwithdrawList = ref([])
const loading = ref(true)
const total = ref(0)
const totalWithdraw = ref(0) // 提现成功总额

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    username: null,
    mobile: null,
    auditStatus: null,
    payChannel: null
  }
})

const { queryParams } = toRefs(data)

/** 查询用户奖励金提现记录列表 */
function getList() {
  loading.value = true
  
  listUserwithdraw(queryParams.value).then(response => {
    userwithdrawList.value = response.rows || []
    total.value = response.total || 0
    loading.value = false
    
    // 计算总提现金额
    calculateTotalWithdraw()
  }).catch(error => {
    console.error('查询失败:', error)
    loading.value = false
    
    // 如果API调用失败，使用模拟数据作为后备
    userwithdrawList.value = [
      {
        id: 1,
        username: 'slam',
        mobile: '13121865386',
        orderNo: '214748364719844',
        withdrawAmount: 1000,
        actualAmount: 990,
        platformFee: 10,
        auditStatus: '到账成功',
        rejectReason: null,
        auditTime: '2025-01-11T23:37:15',
        payChannel: '微信',
        createTime: '2025-01-11T23:37:15'
      },
      {
        id: 2,
        username: 'slam',
        mobile: '13121865386',
        orderNo: '214748364759921',
        withdrawAmount: 100,
        actualAmount: 99,
        platformFee: 1,
        auditStatus: '到账成功',
        rejectReason: null,
        auditTime: '2024-09-20T17:38:00',
        payChannel: '支付宝',
        createTime: '2024-09-20T17:38:00'
      },
      {
        id: 3,
        username: 'slam',
        mobile: '13121865386',
        orderNo: '214748364791800349',
        withdrawAmount: 50,
        actualAmount: 0,
        platformFee: 0,
        auditStatus: '审核不通过',
        rejectReason: '账户信息不匹配',
        auditTime: '2023-11-26T10:57:23',
        payChannel: '银行卡',
        createTime: '2023-11-26T10:57:23'
      },
      {
        id: 4,
        username: 'slam',
        mobile: '13121865386',
        orderNo: '214748364791800350',
        withdrawAmount: 200,
        actualAmount: 200,
        platformFee: 0,
        auditStatus: '审核中',
        rejectReason: null,
        auditTime: null,
        payChannel: '微信',
        createTime: '2025-01-11T10:00:00'
      }
    ]
    total.value = 4
    calculateTotalWithdraw()
    
    if (proxy && proxy.$modal) {
      proxy.$modal.msgError('数据加载失败，显示模拟数据')
    }
  })
}

/** 计算总提现金额 */
function calculateTotalWithdraw() {
  try {
    let totalAmount = 0
    
    if (userwithdrawList.value && Array.isArray(userwithdrawList.value)) {
      userwithdrawList.value.forEach(item => {
        if (item && item.auditStatus === '到账成功') {
          totalAmount += parseFloat(item.actualAmount || 0)
        }
      })
    }
    
    totalWithdraw.value = totalAmount
  } catch (error) {
    console.error('计算总提现金额失败:', error)
    totalWithdraw.value = 0
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value.username = null
  queryParams.value.mobile = null
  queryParams.value.auditStatus = null
  queryParams.value.payChannel = null
  queryParams.value.pageNum = 1
  getList()
}

/** 分页大小改变 */
function handleSizeChange(val) {
  queryParams.value.pageSize = val
  getList()
}

/** 当前页改变 */
function handleCurrentChange(val) {
  queryParams.value.pageNum = val
  getList()
}

/** 格式化金额显示 */
function formatAmount(amount) {
  return parseFloat(amount || 0).toFixed(2)
}

/** 格式化时间显示 */
function formatTime(time) {
  if (!time) return '-'
  const date = new Date(time)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

/** 获取状态类型 */
function getStatusType(status) {
  const statusMap = {
    '审核中': 'warning',
    '审核不通过': 'danger',
    '到账成功': 'success'
  }
  return statusMap[status] || 'info'
}

/** 获取渠道类型 */
function getChannelType(channel) {
  const channelMap = {
    '微信': 'success',
    '支付宝': 'primary',
    '银行卡': 'warning'
  }
  return channelMap[channel] || 'info'
}

/** 审核通过操作 */
function handleApprove(row) {
  proxy.$modal.confirm(`确认通过用户"${row.username}"的提现申请吗？通过后将直接标记为到账成功。`).then(() => {
    const updateData = {
      ...row,
      auditStatus: '到账成功',
      auditTime: new Date().toISOString()
    }
    updateUserwithdraw(updateData).then(response => {
      proxy.$modal.msgSuccess("审核通过成功，已标记为到账成功")
      getList()
    }).catch(error => {
      proxy.$modal.msgError("操作失败")
    })
  }).catch(() => {})
}

/** 审核拒绝操作 */
function handleReject(row) {
  proxy.$prompt('请输入拒绝原因', '审核拒绝', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /.+/,
    inputErrorMessage: '拒绝原因不能为空'
  }).then(({ value }) => {
    const updateData = {
      ...row,
      auditStatus: '审核不通过',
      rejectReason: value,
      auditTime: new Date().toISOString()
    }
    updateUserwithdraw(updateData).then(response => {
      proxy.$modal.msgSuccess("审核拒绝成功")
      getList()
    }).catch(error => {
      proxy.$modal.msgError("操作失败")
    })
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  try {
    if (proxy && proxy.download) {
      proxy.download('order/userwithdraw/export', {
        ...queryParams.value
      }, `user_withdraw_record_${new Date().getTime()}.xlsx`)
    } else {
      proxy.$modal.msgError('导出功能暂时不可用')
    }
  } catch (error) {
    console.error('导出失败:', error)
    proxy.$modal.msgError('导出失败，请重试')
  }
}

// 页面初始化
onMounted(() => {
  getList()
})
</script>
<style scoped>
.withdraw-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 顶部统计卡片 */
.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
  border-radius: 8px;
  padding: 20px;
  color: white;
  width: 200px;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
}

.stat-header {
  font-size: 14px;
  opacity: 0.9;
  margin-bottom: 8px;
}

.stat-amount {
  font-size: 24px;
  font-weight: bold;
}

/* 搜索区域 */
.search-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
  margin-bottom: 16px;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

.search-input {
  width: 180px;
}

.search-select {
  width: 140px;
}

.search-btn {
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
  border: none;
  color: white;
}

/* 操作按钮区域 */
.action-buttons {
  display: flex;
  gap: 12px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

.action-buttons .el-button {
  padding: 8px 16px;
}

/* 表格区域 */
.table-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-tips {
  display: flex;
  gap: 8px;
  align-items: center;
}

.header-stats {
  display: flex;
  gap: 20px;
  align-items: center;
}

.stat-item {
  font-size: 14px;
  color: #606266;
  display: flex;
  align-items: center;
  gap: 4px;
}

.total-text {
  color: #1890ff;
  font-weight: bold;
}

/* 表格内容样式 */
.user-info {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 500;
}

.user-icon {
  color: #1890ff;
  font-size: 16px;
}

.amount-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}

.amount-text {
  color: #52c41a;
  font-weight: 600;
  font-size: 14px;
}

.amount-text.success {
  color: #52c41a;
}

.fee-text {
  color: #fa8c16;
  font-weight: 600;
  font-size: 14px;
}

.amount-label {
  color: #999;
  font-size: 10px;
}

.reject-reason {
  color: #f56c6c;
  font-size: 12px;
}

.time-cell {
  display: flex;
  align-items: center;
  gap: 4px;
  justify-content: center;
}

.time-icon {
  color: #999;
  font-size: 14px;
}

.text-muted {
  color: #999;
  font-size: 12px;
}

/* 表格操作按钮样式 */
.table-action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
}

.table-action-buttons .el-button {
  padding: 4px 8px;
  font-size: 12px;
  min-width: 60px;
}

.table-action-buttons .el-button .el-icon {
  margin-right: 2px;
}

/* 分页 */
.pagination-wrapper {
  display: flex;
  justify-content: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input,
  .search-select {
    width: 100%;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .action-buttons .el-button {
    width: 100%;
  }
  
  .stat-card {
    width: 100%;
  }
}

/* Element Plus 样式覆盖 */
:deep(.el-table) {
  border-radius: 0;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #666;
  font-weight: 500;
}

:deep(.el-pagination) {
  justify-content: center;
}

:deep(.el-button--text) {
  padding: 0;
}
</style>